<template>
  <div class="app-container">
    <!--        <data-group ref="data_group" @select_time="select_time"></data-group>-->
    <!--    <data-group ref="data_group" @select_time="select_time" :show_button="true"></data-group>-->
    <div class="filter-container">
      <el-row>
        <el-input
          v-model="listQuery.key_word"
          placeholder="名称 手机号 地址"
          style="width: 200px;"
          clearable
          class="filter-item"
          @keyup.enter="handleFilter1"
        />
        <el-button
          class="filter-item"
          type="info"
          size="mini"
          style="width: 60px;"
          @click="handleFilter"
        >
          搜索
        </el-button>
        <!--        <span class="" style="margin-left: 20px;font-weight: normal;font-size: 15px">订报类型：</span>-->
        <!--        <el-select v-model="subscriptionTypeFilter" placeholder="订报类型" style="width: 140px">-->
        <!--          <el-option value="all" label="全部"></el-option>-->
        <!--          <el-option v-for="(item, index) in options" :key="index" :label="item.label"-->
        <!--                     :value="item.value"></el-option>-->
        <!--        </el-select>-->
        <!--                <span class="" style="margin-left: 20px;font-weight: normal;font-size: 15px">发货状态：</span>-->
        <!--                <el-select v-model="expressStatusFilter" placeholder="发货状态" style="width: 110px;margin-right: 20px">-->
        <!--                    <el-option value="all" label="全部"></el-option>-->
        <!--                    <el-option v-for="(item, index) in express_list" :key="index" :label="item.label"-->
        <!--                               :value="item.value"></el-option>-->
        <!--                </el-select>-->
        <span class="" style="font-weight: normal;font-size: 15px">订单状态：</span>
        <el-select v-model="payStatusFilter" placeholder="订单状态" style="width: 110px">
          <el-option value="all" label="全部"></el-option>
          <el-option v-for="(item, index) in order_status_list" :key="index" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
        <el-button class="filter-item" type="primary" size="mini" icon="el-icon-plus" style="float: right"
                   @click="getExportList">
          导出报表
        </el-button>
        <!--                <el-button-->
        <!--                        class="filter-item"-->
        <!--                        type="primary"-->
        <!--                        size="mini"-->
        <!--                        icon="el-icon-plus"-->
        <!--                        style="float: right"-->
        <!--                        @click="addDataForm"-->
        <!--                >添加-->
        <!--                </el-button>-->
      </el-row>
    </div>
    <el-table
      empty-text="-"
      v-loading="listLoading"
      :data="filteredData"
      :size="table_size"
      fit
      border
      highlight-current-row
      style="width: 100%;">
      <el-table-column type="index" width="50"/>
      <el-table-column v-for="(ctl,index) in table_ctl" :formatter="ctl.formatter" :sortable="ctl.sortable"
                       :key="index" :label="ctl.label" :prop="ctl.prop" v-if="ctl.visiable"
                       :width="ctl.width ? ctl.width:''"
                       align="center"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px"
                       fixed="right">
        <template slot="header" slot-scope="scope">
          <!--          <span style="margin-right: 15px">操作</span>-->
          <el-tooltip class="item" effect="dark" :hide-after="500" content="设置列" placement="top">
            <el-popover
              placement="left"
              title="设置列"
              width="200"
              trigger="click"
              content="设置列">
              <div v-for="(ctl,index) in table_ctl" :key="index" class="margin-top-xs">
                <el-switch v-model="ctl.visiable" active-text="" inactive-text="" active-color="#13ce66"
                           inactive-color="#666666"></el-switch>
                <span>{{ctl.label}}</span>
              </div>
              <el-button slot="reference" icon="el-icon-setting" circle type="text"></el-button>
            </el-popover>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" :hide-after="500" content="行间距" placement="top">
            <el-popover
              placement="left"
              title="行间距"
              trigger="click"
              content="选择间距">
              <el-radio-group v-model="table_size" size="mini">
                <el-radio-button label="medium">大</el-radio-button>
                <el-radio-button label="small">中</el-radio-button>
                <el-radio-button label="mini">小</el-radio-button>
              </el-radio-group>
              <el-button slot="reference" icon="el-icon-crop" circle type="text"></el-button>
            </el-popover>
          </el-tooltip>
        </template>
        <template slot-scope="scope" class="">
          <!--                    <el-row>-->
          <!--                        <el-select style="width: 60%;" v-model="scope.row.express_status" @change="editData(scope.row)">-->
          <!--                            <el-option :label="i" :value="index" v-for="(i,index) in express_status_list" :key="index">-->
          <!--                            </el-option>-->
          <!--                        </el-select>-->
          <!--                    </el-row>-->
          <el-row>
            <el-button type="text" size="small" v-if="permission.edit" @click="editDataForm(scope.row)">编辑
            </el-button>
            <el-popover
              placement="top"
              v-if="!(scope.row.STATUS===3)"
              :ref="`popover-${scope.$index}`">
              <p>确定删除id为{{scope.row.id}}的数据吗？</p>
              <div style="text-align: center; margin: 0">
                <el-button type="primary" size="mini"
                           @click="removeData(scope.row),scope._self.$refs[`popover-${scope.$index}`].doClose()">
                  确定
                </el-button>
                <el-button type="primary" size="mini"
                           @click="scope._self.$refs[`popover-${scope.$index}`].doClose()">
                  取消
                </el-button>
              </div>
              <el-button v-if="permission.delete" type="text" size="small" slot="reference">删除</el-button>
            </el-popover>
            <!--                        <el-button type="text" v-if="scope.row.pay_status === 1 && permission.edit" size="small"-->
            <!--                                   @click="retireForm(scope.row)">退款-->
            <!--                        </el-button>-->
          </el-row>

        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      style="width: 100%;"
      custom-class="dialogwidth">
      <el-form
        ref="dataForm"
        :model="form"
        label-position="left"
        label-width="150px">
        <div class="lb">
          <el-form-item label="订单ID：">
            <el-input v-model="form.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名称：">
            <el-input v-model="form.user_name"></el-input>
          </el-form-item>
          <el-form-item label="联系电话：">
            <el-input v-model="form.phone" oninput="value = value.match(/^\d+/)" maxlength="11"></el-input>
          </el-form-item>
          <el-form-item label="详细地址：">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
          <el-form-item label="推荐人：">
            <el-input v-model="form.referrer"></el-input>
          </el-form-item>
          <el-form-item label="办理情况：">
            <el-input type="textarea" :autosize="{ minRows: 2}" v-model="form.desc"></el-input>
          </el-form-item>
          <el-form-item label="受理人名称：">
            <el-input v-model="form.school"></el-input>
          </el-form-item>
          <el-form-item label="完成情况：">
            <el-input type="textarea" :autosize="{ minRows: 2}" v-model="form.complete_desc"></el-input>
          </el-form-item>
          <el-form-item label="客户评星：">
            <el-input v-model="form.evaluation" oninput="value = value.match(/[0-5]/)" maxlength="1"></el-input>
          </el-form-item>
          <el-form-item label="客户评价：">
            <el-input type="textarea" :autosize="{ minRows: 2}" v-model="form.evaluation_desc"></el-input>
          </el-form-item>
          <el-form-item label="订单状态：">
            <el-select v-model="form.status" placeholder="订单状态" style="width: 110px">
              <el-option v-for="(item, index) in order_status_list" :key="index" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input v-model="form.remark"></el-input>
          </el-form-item>
          <!--          <el-form-item label="用户名：">-->
          <!--            <el-input v-model="form.username"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="密码：">-->
          <!--            <el-input v-model="form.password" type="password" show-password></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="角色：">-->
          <!--            <el-select style="width: 100%;" v-model="form.roles" multiple>-->
          <!--              <el-option :label="i.name" :value="i.id" v-for="(i,index) in role_list" :key="index">-->
          <!--              </el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="号码：">-->
          <!--            <el-input v-model="form.mobile"></el-input>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="过期时间：">-->
          <!--            <el-date-picker v-model="form.EXPIRED_DATE" value-format="yyyy-MM-dd"></el-date-picker>-->
          <!--          </el-form-item>-->
          <!--                    <el-form-item label="备注：">-->
          <!--                        <el-input v-model="form.remark"></el-input>-->
          <!--                    </el-form-item>-->
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?addData():editData1()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="表格列编辑"
      :visible.sync="table_dialog_form_visiable"
      style="width: 100%;"
      custom-class="dialogwidth">
      <el-form
        ref="dataForm"
        label-position="right"
        label-width="200px">
        <div class="lb">
          <el-form-item :label="ctl.label + '：'" v-for="(ctl,index) in table_ctl" :key="index">
            <el-switch v-model="ctl.visiable" active-text="可见" inactive-text="不可见" active-color="#13ce66"
                       inactive-color="#666666"></el-switch>
          </el-form-item>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="table_dialog_form_visiable = false" type='primary'>确定</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :page-sizes="[20,50,99]"
      :page-size="99"
      :limit.sync="listQuery.limit"
      @pagination="getDataList"
    />
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination/index' // secondary package based on el-pagination
  import dataGroup from '@/views/manage/components/dataGroup'
  import {order_table_ctl, options, express_list, order_status_list} from '@/utils/table_ctl'
  import {getData, getDataDetail, removeData, editData, addData} from '@/api/system'
  import Vue from 'vue'
  import {getPermission} from '@/utils/permission'

  export default {
    components: {Pagination, dataGroup},
    data() {
      return {
        uri: 'order',
        table_size: 'mini',
        list: [],
        export_list: [],
        total: 0,
        routeID: 21,
        permission: {},
        role_list: [],
        express_status_list: ['未发货', '已发货'],
        listLoading: false,
        table_dialog_form_visiable: false,
        month: '', // 初始化 month
        price: '', // 初始化 price
        form: {
          charge_standard: '', // 初始化 form.charge_standard
        },
        dialogFormVisible: false,
        textMap: {
          edit: '编辑',
          create: '添加'
        },
        table_ctl: order_table_ctl,
        // 默认表单数据
        dialogStatus: '',
        listQuery: {
          page: 1,
          limit: 99,
          start_time: null,
          end_time: null
        },
        options: options,
        order_status_list: order_status_list,
        // express_list: express_list,
        payStatusFilter: 'all',
      }
    },
    computed: {
      filteredData() {
        // if ( this.expressStatusFilter === 'all' && this.payStatusFilter === 'all' && !this.listQuery.key_word) {
        if (this.payStatusFilter === 'all' && !this.listQuery.key_word) {
          return this.list; // 如果没有选择筛选项且没有关键字，返回全部数据
        }

        // 根据选择器筛选
        let filteredData = this.list;

        if (this.payStatusFilter !== 'all') {
          filteredData = filteredData.filter(item => item.status == this.payStatusFilter);
        }

        // 根据关键字搜索
        if (this.listQuery.key_word) {
          const keyword = this.listQuery.key_word.toLowerCase();
          return filteredData.filter(item => {
            return (
              item.user_name.toLowerCase().includes(keyword) || // 根据用户名搜索
              item.acceptor_name.toLowerCase().includes(keyword) || // 根据用户名搜索
              item.phone.toLowerCase().includes(keyword) ||    // 根据手机号搜索
              item.address.toLowerCase().includes(keyword)       // 根据地区搜索
            );
          });
        }

        return filteredData;
      },
    },

    created() {
    },
    mounted() {
      this.getDataList()
      this.permission = getPermission(this.routeID)
    },
    methods: {
      handleFilter() {
        this.listQuery.page = 1
        this.getDataList()
      },
      handleFilter1() {
        // 进行数据过滤，基于 listQuery.key_word 进行搜索
        this.filteredData = this.list.filter(item => {
          const keyword = this.listQuery.key_word.toLowerCase();
          return (
            item.user_name.toLowerCase().includes(keyword) || // 根据用户名搜索
            item.acceptor_name.toLowerCase().includes(keyword) || // 根据用户名搜索
            item.phone.toLowerCase().includes(keyword) ||    // 根据手机号搜索
            item.address.toLowerCase().includes(keyword)       // 根据地区搜索
          );
        });
      },
      // 获取数据
      getDataList() {
        let _this = this
        _this.listLoading = true
        let para = _this.cleanObj(Object.assign({}, _this.listQuery))
        getData(_this.uri, para).then(response => {
          _this.list = []
          let items = response.items
          for (let li in items) {
            let i = items[li]
            for (let j in i) {
              if (i[j] && i[j].c) {
                i[j] = i[j].c.join('')
              }
            }
            _this.list.push(i)
          }
          _this.total = response.totalCount
          _this.listLoading = false
        })
      },
      // 添加数据
      addData() {
        let _this = this
        let para = Object.assign({}, _this.form)
        // para.roles = [para.roles]
        addData(_this.uri, para).then((res) => {
          if (res.code === 20000) {
            _this.$message({
              type: 'success',
              message: res.message
            })
            _this.dialogFormVisible = false
            _this.getDataList()
          }
        })

      },
      // 显示添加表单
      addDataForm() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      // 显示编辑表单
      editDataForm(row) {
        this.resetForm()
        this.form = Object.assign({}, row)
        this.dialogStatus = 'edit'
        this.dialogFormVisible = true
      },
      // retireForm(row) {
      //     let _this = this
      //     _this.$confirm('确定退款ID为「' + row.id + '」的订单吗?', '提示', {
      //         confirmButtonText: '确定',
      //         cancelButtonText: '取消',
      //         type: 'warning'
      //     }).then(() => {
      //         let para = {
      //             order_id: row.id
      //         }
      //         let url = 'order/refund'
      //         addData(url, para).then((res) => {
      //             if (res.code === 20000) {
      //                 _this.$message({
      //                     type: 'success',
      //                     message: res.message
      //                 })
      //                 _this.getDataList()
      //             }
      //         })
      //     }).catch(() => {
      //     })
      // },
      retireForm(row) {
        let _this = this;
        const verificationCode = this.generateVerificationCode();

        _this.$prompt(`确定退款ID为${row.id}、金额为${row.total_fee}的订单吗?\n验证码: ${verificationCode}`, '退款确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9]{6}$/, // 正则表达式，用于验证输入
          inputErrorMessage: '验证码不正确', // 验证失败时显示的错误消息
        }).then(({value}) => {
          if (value === verificationCode) {
            // 验证码匹配，执行退款操作
            let para = {
              order_id: row.id,
              verification_code: value,
            };
            let url = 'order/refund';
            addData(url, para).then((res) => {
              if (res.code === 20000) {
                _this.$message({
                  type: 'success',
                  message: res.message,
                });
                _this.getDataList();
              }
            });
          } else {
            _this.$message.error('验证码不匹配');
          }
        }).catch(() => {
          // 取消操作
        });
      },
      generateVerificationCode() {
        let code = '';
        const length = 6; // 验证码的长度

        // 生成六位数字验证码
        for (let i = 0; i < length; i++) {
          code += Math.floor(Math.random() * 10); // 生成 0 到 9 之间的随机数字
        }

        return code;
      },
      // 重置表单
      resetForm() {
        this.form = this.$options.data().form
      },
      // 编辑发货状态
      editData(row) {
        let _this = this
        // let para = Object.assign({}, _this.form)
        let para = {
          id: row.id,
          express_status: row.express_status,
        }
        editData(_this.uri, para).then((res) => {
          if (res.code === 20000) {
            _this.$message({
              type: 'success',
              message: res.message
            })
            _this.dialogFormVisible = false
            _this.getDataList()
          }
        })
      },
      // 编辑数据
      editData1() {
        let _this = this;

        // 创建一个新的对象来存储需要传输的字段
        let para = {
          id: _this.form.id,
          receiver: _this.form.receiver,
          phone: _this.form.phone,
          region: _this.form.region,
          province_city: _this.form.province_city,
          address: _this.form.address
        };

        editData(_this.uri, para).then((res) => {
          if (res.code === 20000) {
            _this.$message({
              type: 'success',
              message: res.message
            });
            _this.dialogFormVisible = false;
            _this.getDataList();
          }
        });
      },

      // editData1() {
      //     let _this = this
      //     let para = Object.assign({}, _this.form)
      //     editData(_this.uri, para).then((res) => {
      //         if (res.code === 20000) {
      //             _this.$message({
      //                 type: 'success',
      //                 message: res.message
      //             })
      //             _this.dialogFormVisible = false
      //             _this.getDataList()
      //         }
      //     })
      // },
      // 删除数据
      removeData(row) {
        let _this = this
        removeData(_this.uri, row).then((res) => {
          if (res.code === 20000) {
            _this.$message({
              type: 'success',
              message: '删除成功!'
            })
            _this.getDataList()
          }
        })

      },
      // 去除无用数据
      cleanObj(obj) {
        for (var ob in obj) {
          if (obj[ob] == null || obj[ob] === '') {
            delete obj[ob]
          } else if (typeof obj[ob] === 'object') {
            obj[ob] = this.cleanObj(obj[ob])
          }
        }
        return obj
      },
      select_time(evt) {
        console.log(evt)
      },
      // formatJson(filterVal, jsonData) {
      //     return jsonData.map(v => filterVal.map(j => {
      //         return v[j]
      //     }))
      // },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'status') {
            // 映射 pay_status 的 label
            return order_status_list.find(item => item.value === v[j]).label;
          }
            // else if (j === 'actual_paid') {
            //   return v[j] / 100;
            // }
            // else if (j === 'start_date' || j === 'end_date') {
            //   // return v[j] ? v[j].slice(0, 7) : ''; // 添加检查以防止值为 null 或 undefined
            //   return v[j]
          // }
          else if (j === 'create_time' || j === 'update_time') {
            // return v[j] ? v[j].slice(0, 10) : ''; // 添加检查以防止值为 null 或 undefined
            return v[j]
          } else {
            return v[j];
          }
        }));
      },
      exportToExcel() {
        let _this = this
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = order_table_ctl.map(item => item.prop);
          const data = _this.formatJson(tHeader, _this.export_list) // 导出函数接收的数组
          console.log(data,_this.export_list)
          const tHeader1 = order_table_ctl.map(item => item.label);
          try {
            excel.export_json_to_excel({
              header: tHeader1,
              data,
              filename: 'excel-list',
              autoWidth: true,
              bookType: 'xlsx'
            });
          } catch (error) {
            console.error('Excel导出错误:', error);
          }
        });
      },
      getExportList() {
        let _this = this
        _this.listLoading = true
        let para = { page: 1,
          limit: 99,
          start_time: null,
          end_time: null}
        getData('order/export_list', para).then(response => {
          _this.export_list = response.items
          console.log(_this.export_list)
          _this.exportToExcel()
          _this.listLoading = false
        })
      },

    }
  }
</script>

<style>

</style>
